//
//  YJResetPWDVC.m
//  YJB
//
//  Created by 高卫明 on 16/7/9.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "YJResetPWDVC.h"
#import "YJNetworkTool.h"
#import "YJUserDefaultTool.h"
#import "YJLoginVC.h"
#import "YJBaseNav.h"
#import "AppDelegate.h"

@interface YJResetPWDVC ()

@property (strong, nonatomic)UITextField *passWord;
@property (strong,nonatomic) UITextField *insurePWD;
@property(nonatomic,strong)UIButton *checkBtn;
@property(nonatomic,weak)AppDelegate *appDelegate;
@end

@implementation YJResetPWDVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    self.navigationItem.title = @"重设密码";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(backItemClick) image:@"back_black" highImage:nil title:nil];
    
    self.passWord = [[UITextField alloc]initWithFrame:CGRectMake(20, 79, IPHONE_W - 40, 40)];
    UIView *leftViewOne = [[UIView alloc]init];
    leftViewOne.width = 10;
    self.passWord.leftView = leftViewOne;
    self.passWord.leftViewMode = UITextFieldViewModeAlways;
    [self.passWord setBackground:Image(@"login_inputView_bg")];
    _passWord.placeholder = @"密码";
    [_passWord becomeFirstResponder];
    _passWord.keyboardType =  UIKeyboardTypeNumberPad;
    _passWord.secureTextEntry = YES;
    [self.view addSubview:_passWord];
    
    self.insurePWD = [[UITextField alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(self.passWord.frame) + 15, IPHONE_W - 40, 40)];
    UIView *leftViewTwo = [[UIView alloc]init];
    leftViewTwo.width = 10;
    self.insurePWD.leftView = leftViewTwo;
    self.insurePWD.leftViewMode = UITextFieldViewModeAlways;
    [self.insurePWD setBackground:Image(@"login_inputView_bg")];
    _insurePWD.placeholder = @"确认密码";
    _insurePWD.keyboardType =  UIKeyboardTypeNumberPad;
    _insurePWD.secureTextEntry = YES;
    [self.view addSubview:self.insurePWD];

    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(self.insurePWD.frame) + 10, IPHONE_W - 40, 40)];
    [btn setBackgroundImage:Image(@"button_icon") forState:UIControlStateNormal];
    [btn setBackgroundImage:Image(@"button_icon_HL") forState:UIControlStateHighlighted];
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(ensureBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    self.checkBtn = btn;

}


- (void)backItemClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)ensureBtn
{
    if (_passWord.text.length == 0 )
    {
        [MBProgressHUD showError:@"请输入密码" ];
        return;
    }
    if (![_passWord.text isEqualToString:_insurePWD.text])
    {
        [MBProgressHUD showError:@"两次输入密码不一致"];
        return;
    }
    //先根据手机号码获取对应的用户名
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"action"] = @"get_username_by_phone";
    params[@"makegold"] = @{
                            @"phone":_telephone,
                            @"phone_info":@"iOS",
                            @"user_info":@"admin",
                            @"md5_key":[[[@"admin"stringByAppendingString:@"iOS"]stringByAppendingString:appMd5Key] md5]};
    MyLog(@" ======== %@",params);
    [MBProgressHUD showMessage:@""];
    [YJNetworkTool postWithUrl:NEWURL(@"user.php") parameters:params success:^(id responseObject)
     {
         MyLog(@"responseObject =======  %@",responseObject);
         NSString *code = responseObject[@"return"][@"code"];
         if (code.integerValue == 200)
         {
             NSString *userName = responseObject[@"return"][@"data"][@"UserName"];
             [self setupPassWordWithUserName:userName];
         }else
         {
             [MBProgressHUD hideHUD];
             NSString *message = responseObject[@"return"][@"message"];
             [MBProgressHUD showError:message];
         }

     } failure:^(NSError *error) {
         [MBProgressHUD hideHUD];
         [MBProgressHUD showError:@"网络不佳，稍后重试" toView:self.view];
     }];
    
}

- (void)setupPassWordWithUserName:(NSString *)userName
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"action"] = @"set_resetpass";
    params[@"makegold"] = @{@"user_info":@"admin",
                            @"username":userName,
                            @"password":[_passWord.text md5],
                            @"phone_info":@"iOS",
                            @"md5_key":[[[@"admin"stringByAppendingString:@"iOS"]stringByAppendingString:appMd5Key] md5]};

    [YJNetworkTool postWithUrl:NEWURL(@"user.php") parameters:params success:^(id responseObject)
     {
         [MBProgressHUD hideHUD];
         NSString *code = responseObject[@"return"][@"code"];
         if (code.integerValue == 200)
         {
             NSString *message = responseObject[@"return"][@"message"];
             [MBProgressHUD showSuccess:message];
             if (_isPushFromSetting)
             {
                 self.appDelegate.isConnectWebsocket = NO;
                 self.appDelegate.wSocket.delegate = nil;
                 [_appDelegate.wSocket close];
                 self.appDelegate.cardMessages = nil;
                 [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
                 [YJKeychainTool savePassword:@""];
                 [YJUserDefaultTool saveLoginStatus:NO];
                 YJBaseNav *nav = [[YJBaseNav alloc] initWithRootViewController:[YJLoginVC new]];
                 [UIApplication sharedApplication].keyWindow.rootViewController = nav;

             }else
             {
                 [NOTIFICATIONCENTER postNotificationName:YJUserDidChangePassWordNotification object:nil];
                 [self.navigationController popToRootViewControllerAnimated:YES];
             }
         }else
         {
             NSString *message = responseObject[@"return"][@"message"];
             [MBProgressHUD showError:message toView:self.view];
         }
         
     } failure:^(NSError *error) {
         [MBProgressHUD hideHUD];
         [MBProgressHUD showError:@"网络不佳，稍后重试" toView:self.view];
     }];

}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
